package com.atlanta.adopt;

import java.util.concurrent.ExecutionException;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewManager;

import android.view.ViewGroup.LayoutParams;
import android.widget.Button;

import android.widget.Button;

import android.widget.GridLayout;
import android.widget.ImageButton;

import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import android.view.View;


public class HMBrowserActivity extends Activity implements View.OnClickListener {
	 private String[] dogLinks;
	 private Bitmap[] dogPics;
	 private Elements dogImageURLs;
	 private int fetchSize = 70;
	 protected int returnedanimals;
	 protected Document doginfo = null;
	 protected String URL ;
	 public void generateViewFromLink(int linkIdx ){
		
		
		try {
			doginfo = new NetTask().execute(dogLinks[linkIdx]).get();
			 if(doginfo==null){
					AlertDialog cantconnect = new AlertDialog.Builder(this).create();
					cantconnect.setMessage("AdoptAtlanta could not update at this time ");
					cantconnect.show();
					return;	
			 }
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Elements fields = doginfo.select("td.detail-value span");
		Elements fieldnames = doginfo.select("td.detail-label");
		
		
		String name = doginfo.select("td.detail-animal-name").first().text();
		Animal dog = new Animal();
		for(int i =0;i<fieldnames.size();i++){
			if(fieldnames.get(i).text().equals("Animal ID")){
				dog.setID(fields.get(i).text());
				
			}else if(fieldnames.get(i).text().equals("Breed")){
				dog.setBreed(fields.get(i).text());
			}else if(fieldnames.get(i).text().equals("Age")){
				dog.setAge(fields.get(i).text());
			}else if(fieldnames.get(i).text().equals("Sex")){
				dog.setSex(fields.get(i).text());
			}else if(fieldnames.get(i).text().equals("Size")){
				dog.setSize(fields.get(i).text());
			}else if(fieldnames.get(i).text().equals("Color")){
				dog.setColor(fields.get(i).text());
			}else if(fieldnames.get(i).text().equals("Declawed")){
				dog.setDeclawed(fields.get(i-1).text());
			}else if(fieldnames.get(i).text().equals("Site")){
				dog.setSite(fields.get(i).text());
			}else if(fieldnames.get(i).text().equals("Location")){
				dog.setLocation(fields.get(i).text());
			}else if(fieldnames.get(i).text().contains("Intake")){
				dog.setIntakeDate(fields.get(i-1).text());
			}else if(fieldnames.get(i).text().equals("Adoption Price")){
				dog.setAdoptionprice(fields.get(i-1).text());
			}
			Log.d("lol",fieldnames.get(i).text());
		}
		dog.setName(name);
		//dog.setPic(dogPics[linkIdx]);
		//dogImageURLs.get(i).attr("src").substring(0,dogImageURLs.get(i).attr("src").length()-8)
		String url = dogImageURLs.get(linkIdx).attr("src").substring(0,dogImageURLs.get(linkIdx).attr("src").length()-8);
		url+=".jpg";
		Log.d("yasrhsafdsa", url);
		try {
			dog.setPic((Bitmap)new DownloadImageTask().execute(url).get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dog.setLink(dogLinks[linkIdx]);
		((Globals)this.getApplication()).paramAnimalForPetInfo = dog;
		Intent intent = new Intent(this, PetInfoDisplayActivity.class);
		startActivityForResult(intent,0);
		//call thomas activity with Doggy d;
	 }

	 private Button back;
	 private Button hminfo;
	 public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainscreen);
		URL = ((Globals)this.getApplication()).kennelAnimalsDisplayPageLink;
	
		((TextView)findViewById(R.id.title)).setText(((Globals)this.getApplication()).kennelAnimalsDisplayPageTitle);
	    //gonna set some content view
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		back = (Button)findViewById(R.id.back);
		back.setOnClickListener(this);
		 
		hminfo = (Button)findViewById(R.id.hminfo);
		 hminfo.setOnClickListener(this);
		new parseTask().execute();
		
		 
	 }
	 public void tablesetup(){
		 TableLayout tl = (TableLayout) findViewById(R.id.animals);
		 TableRow tr =new TableRow(this);
		 tr.setLayoutParams(new LayoutParams(
                 LayoutParams.FILL_PARENT,
                 LayoutParams.WRAP_CONTENT));
		 for(int i=0;i<dogPics.length && i< fetchSize;i++){
			
			ImageButton image = new ImageButton(this);
			image.setBackgroundDrawable(new BitmapDrawable(dogPics[i]));
			image.setId(i);
			image.setLayoutParams( new TableRow.LayoutParams(110, 110));
			image.setOnClickListener(new OnClickListener(){
		          public void onClick(View view) {
		        	  generateViewFromLink(view.getId());
		          }});
			
			int imagesInRow = 4;
			Display display = getWindowManager().getDefaultDisplay(); 
			int width = display.getWidth();  // deprecated
			int imwidth = width/imagesInRow;
			image.getLayoutParams().width = imwidth;
			image.getLayoutParams().height = imwidth;
			tr.addView(image);
			if(i==(dogPics.length-1) || (i%imagesInRow == 0 && i!=0)){
				
				 tr = new TableRow(this);
				 tr.setLayoutParams(new LayoutParams(
                         LayoutParams.FILL_PARENT,
                         LayoutParams.WRAP_CONTENT));
				 tl.addView(tr,new TableLayout.LayoutParams(
		                    LayoutParams.FILL_PARENT,
		                    LayoutParams.WRAP_CONTENT));
			}
			//GridLayout g = (GridLayout) findViewById(R.id.animals);
			//g.addView(image);
		 }
	 }
	 //this will set the pic array as well as the links for each pic
	 //this will set the pic array as well as the links for each pic
	 public boolean parseDogs(Document d){
		// String baseURL = "www.petango.com/webservices/adoptablesearch/";
		if(d==null)
			return false;
		
		 Elements dogElts = d.select("div.list-animal-name");
		 
		 dogLinks = new String [dogElts.size()];
		 dogPics = new Bitmap[dogElts.size()];
		 this.returnedanimals = dogElts.size();
		 //first populate dog links
		
		 
		 for(int i = 0;i<dogElts.size() && i< fetchSize;i++){
			 dogLinks[i] = dogElts.get(i).select("a[href]").first().attr("abs:href");
		 }
		 
		 
		 //now for getting the pictures
		 dogImageURLs = d.select("div.list-animal-photo-block img");
		 for(int i = 0;i<dogImageURLs.size() && i< fetchSize;i++){
			
			 try {
				dogPics[i] = new DownloadImageTask().execute(dogImageURLs.get(i).attr("src")).get();
				if(dogPics==null){
						return false;
				 }
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 
		 
		 return true;
	 }
	 
	public void onClick(View v) {
		if(v == back) {
			finish();
		} else if(v == hminfo) {
			Intent HowellInfoIntent = new Intent(this, HowellInfoActivity.class);
			startActivity(HowellInfoIntent);
		}
	}
	public void displayerror(){
		AlertDialog cantconnect = new AlertDialog.Builder(this).create();
		cantconnect.setMessage("AdoptAtlanta could not update at this time ");
		cantconnect.show();
		return;
	}
	private class parseTask extends AsyncTask<String, Void, Bitmap>{
		ProgressDialog dialog; 
		boolean res;
		@Override
		protected void onPreExecute(){
			dialog= ProgressDialog.show(HMBrowserActivity.this, "", 
                    "Querying Kennel databases...", true);
		}
		@Override
		protected void onPostExecute(Bitmap b){
			if(!res){
				displayerror();
				dialog.dismiss();
				return;
			}
			dialog.show();
			tablesetup();
			dialog.dismiss();
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			
			 NetTask dogGroupFetcher = new NetTask();
			 try {
				 
				res = parseDogs(dogGroupFetcher.execute(URL).get());
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		
	}
}
